package com.csxy.chy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csxy.chy.entity.vo.*;
import com.csxy.chy.service.EduChapterService;
import com.csxy.chy.service.EduVideoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csxy.chy.entity.EduCourse;
import com.csxy.chy.entity.EduCourseDescription;
import com.csxy.chy.mapper.EduCourseMapper;
import com.csxy.chy.service.EduCourseService;
import com.csxy.chy.service.EduCourseDescriptionService;
import com.csxy.chy.exception.MyException;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//添加课程基本信息
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {
    
    @Autowired
    private EduCourseDescriptionService eduCourseDescriptionService;
    @Autowired
    private EduVideoService eduVideoService;
    @Autowired
    private EduChapterService eduChapterService;
    
    @Override
    public String addCourseInfo(CourseInfoForm courseInfoForm) {
        //向课程表里添加课程基本信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoForm,eduCourse);
        eduCourse.setIsDeleted(0); // 补充：设置逻辑删除字段为0
        int result = baseMapper.insert(eduCourse);

        if (result == 0) {
            throw new MyException(20001, "添加课程失败");
        }

        //获取添加之后课程信息的id
        String cid = eduCourse.getId();
        //向课程简介表里面添加课程简介
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setDescription(courseInfoForm.getDescription());
        //手动设置描述课程表的id，与上面的课程信息表id关联
        eduCourseDescription.setId(cid);
        eduCourseDescriptionService.save(eduCourseDescription); // ★★★ 关键
        return cid;
    }

    @Override
    public CourseInfoForm getCourseInfoById(String courseId) {
        //根据ID查询课程
        EduCourse eduCourse = baseMapper.selectById(courseId);
        
        //判断查询结果是否为空
        if (eduCourse == null) {
            throw new MyException(20001, "未找到对应课程信息，课程ID: " + courseId);
        }
        
        //定义一个空的课程对象
        CourseInfoForm courseInfoForm = new CourseInfoForm();
        //属性copy
        BeanUtils.copyProperties(eduCourse, courseInfoForm);
        
        //查询简介并赋值
        EduCourseDescription description = eduCourseDescriptionService.getById(courseId);
        if (description != null) {
            courseInfoForm.setDescription(description.getDescription());
        }

        return courseInfoForm;
    }

    @Override
    public void updateCourseInfo(CourseInfoForm courseInfoForm) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoForm,eduCourse);
        baseMapper.updateById(eduCourse);
        //修改描述信息
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setDescription(courseInfoForm.getDescription());
        eduCourseDescription.setId(courseInfoForm.getId());
        eduCourseDescriptionService.updateById(eduCourseDescription);
    }

    @Override
    public boolean removeCourse(String id) {
        //1.根据课程id删除小节
        eduVideoService.removeVideoByCourseId(id);
        //2.更具课程id删除章节
        eduChapterService.removeChapterByCourseId(id);
        //3.根据课程id删除课程描述
        eduCourseDescriptionService.removeById(id);
        //4.根据课程id删除课程本身
        int result = baseMapper.deleteById(id);
        if (result > 1){
            return true;
        }else {
            throw new MyException(20001, "删除失败");
        }
    }

    @Override
    public void pageQuery(Page<EduCourse> pageCourse, CourseQuery courseQuery) {
        //构建条件
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        String title = courseQuery.getTitle();
        String status = courseQuery.getStatus();
        if (!title.isEmpty()) {
            queryWrapper.like("title",title);
        }
        if (!status.isEmpty()) {
            queryWrapper.eq("status",status);
        }
        queryWrapper.orderByDesc("gmt_modified");
        baseMapper.selectPage(pageCourse, queryWrapper);
    }
    @Autowired
    private EduCourseMapper eduCourseMapper;

    @Override
    public CoursePublishVo getPublishCourseInfo(String id) {
        return eduCourseMapper.getPublishCourseInfo(id);
    }

    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {
        return baseMapper.getBaseCourseInfo(courseId);
    }

    //热门课程查询，浏览量降序，
    @Override
/*    @Cacheable(key = "'selectHotCourse'", value = "course")*/
    public List<EduCourse> selectHotCourse() {
        //查询八条热门课程
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("view_count");
        wrapper.last("limit 8");
        return baseMapper.selectList(wrapper);
    }

    @Override
    public Map<String, Object> getCourseFrontInfo(Page<EduCourse> pageCourse, CourseFrontVo courseFrontVo) {
        //拼接条件查询
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(courseFrontVo.getSubjectId())){
            wrapper.eq("subject_parent_id",courseFrontVo.getSubjectId());
        }
        if (StringUtils.isNotEmpty(courseFrontVo.getSubjectId())){
            wrapper.eq("subject_id",courseFrontVo.getSubjectId());
        }
        if (StringUtils.isNotEmpty(courseFrontVo.getBuyCountSort())){
            wrapper.orderByDesc("buy_count");
        }
        if (StringUtils.isNotEmpty(courseFrontVo.getPriceSort())){
            wrapper.orderByDesc("price");
        }
        if (StringUtils.isNotEmpty(courseFrontVo.getGmtCreateSort())){
            wrapper.orderByDesc("gmt_create");
        }
        eduCourseMapper.selectPage(pageCourse,wrapper);
        Map<String,Object> map = new HashMap<>();
        long total = pageCourse.getTotal();//总记录数
        List<EduCourse> courseList = pageCourse.getRecords();//数据集合
        long size = pageCourse.getSize();//每页记录数
        long current = pageCourse.getCurrent();//当前页
        long pages = pageCourse.getPages();//总页数
        boolean hasPrevios = pageCourse.hasPrevious();//是否有上一页
        boolean hasNext = pageCourse.hasNext();//是否有下一页
        map.put("total",total);
        map.put("list",courseList);
        map.put("size",size);
        map.put("current",current);
        map.put("pages",pages);
        map.put("hasPrevios",hasPrevios);
        map.put("hasNext",hasNext);

        return map;
    }
}
